const { verifyToken } = require('../utils/jwt');

// 认证中间件
const auth = async (ctx, next) => {
  try {
    const token = ctx.header.authorization?.split(' ')[1];
    if (!token) {
      ctx.status = 401;
      ctx.body = {
        code: 401,
        message: '未提供认证令牌'
      };
      return;
    }

    const decoded = verifyToken(token);
    ctx.state.user = decoded;
    await next();
  } catch (error) {
    ctx.status = 401;
    ctx.body = {
      code: 401,
      message: '认证失败'
    };
  }
};

module.exports = auth; 